import Vue from 'vue'
import Vuex from 'vuex'
import persist from 'vuex-persistedstate'
import $toast from '@/components'
Vue.use(Vuex)
Vue.use($toast)

export default new Vuex.Store({
  state: {
    backColor: 'orange',
    color: ['red', 'green', 'blue', 'yellow', 'pink', 'orange'],
    books: [],
    content: '',
    checkedBooks: []
  },
  getters: {
    books(state) {
      let arr = state.books.filter(item => {
        return item.name.includes(state.content)
      })
      return arr
    }
  },
  mutations: {
    changeBackColor(state) {
      let i = Math.round(Math.random()*5)
      state.backColor = state.color[i]
    },

    changeBooks(state, value) {
      state.books = value
    },

    checkBook(state, item) {
      if(state.checkedBooks.length === 0) {
        state.checkedBooks.push(item)
        // alert('添加成功')
        Vue.$toast.show('添加成功')
      } else {
        var flag = false
        state.checkedBooks.forEach(el => {
          if(el.id == item.id) {
            flag = true // true表示列表中已经存在该书了
          }
        })

        if(flag) {
          Vue.$toast.show('该书已存在')
        } else {
          state.checkedBooks.push(item)
          Vue.$toast.show('添加成功')
        }
      }

      setTimeout(() => {
        Vue.$toast.hide()
      }, 1000);
    }
  },
  actions: {
  },
  modules: {
  },

  plugins: [persist()]
})
